package org.leetcode.middle.leetcode102;

import org.leetcode.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class Solution2 {

    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> levelOrder(TreeNode root) {

        BFS(root);

        return res;
    }

    private void BFS(TreeNode root) {

        if (root == null) {
            return;
        }

        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.add(root);

        while (!deque.isEmpty()) {
            int size = deque.size();
            List<Integer> item = new ArrayList<>();
            while (size > 0) {
                TreeNode node = deque.poll();
                item.add(node.val);
                size--;

                if (node.left != null) {
                    deque.add(node.left);
                }

                if (node.right != null) {
                    deque.add(node.right);
                }
            }
            res.add(item);
        }

    }

}
